package com.benyanyi.loglib

import android.app.Application
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import java.io.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author myLove
 * @time 2017/10/31 10:41
 * @e-mail ben@yanyi.red
 * @overview
 */
internal object BaseLog {
    private const val MAX_LENGTH = 4000
    fun printDefault(type: LogType, tag: String, msg: String) {
        var index = 0
        val length = msg.length
        val countOfSub = length / MAX_LENGTH
        if (countOfSub > 0) {
            for (i in 0 until countOfSub) {
                val sub = msg.substring(index, index + MAX_LENGTH)
                printSub(type, tag, sub)
                index += MAX_LENGTH
            }
            printSub(type, tag, msg.substring(index, length))
        } else {
            printSub(type, tag, msg)
        }
    }

    private fun printSub(type: LogType, tag: String, sub: String) {
        if (Jlog.mConfig.isShowLog || Jlog.IS_INIT) {
            when (type) {
                LogType.V -> Log.v(tag, sub)
                LogType.D -> Log.d(tag, sub)
                LogType.I -> Log.i(tag, sub)
                LogType.W -> Log.w(tag, sub)
                LogType.E -> Log.e(tag, sub)
                LogType.A -> Log.wtf(tag, sub)
            }
        }
        if (!Jlog.mConfig.isWrite) {
            return
        }
        if (!Jlog.mConfig.isShowWrite && Jlog.mConfig.isShowLog) {
            return
        }
        writeLog(tag, sub)
    }

    /**
     * 记录报错日志
     */
    fun writeError(tag: String, throwable: Throwable) {
        val writer = StringWriter()
        val printWriter = PrintWriter(writer)
        throwable.printStackTrace(printWriter)
        var cause = throwable.cause
        while (cause != null) {
            cause.printStackTrace(printWriter)
            cause = cause.cause
        }
        printWriter.close()
        val s = writer.toString()
        writeLog(tag, s)
    }

    /**
     * 记录日志
     */
    @JvmStatic
    fun writeLog(tag: String, exceptionDescription: String?) {
        try {
            val ROOT_PATH: String
            if (TextUtils.isEmpty(Jlog.mConfig.writeRootPath) || Jlog.mConfig.writeRootPath.equals(
                    "null",
                    ignoreCase = true
                )
            ) {
                val application =
                    Class.forName("android.app.ActivityThread").getMethod("currentApplication")
                        .invoke(null, *(null ?: arrayOfNulls<Any>(0))) as Application
                val packageName = application.packageName
                if (exceptionDescription == null || TextUtils.isEmpty(packageName)) {
                    return
                }
                val fileName: String
                val split = packageName.split("\\.".toRegex()).toTypedArray()
                fileName = split[split.size - 1]
                ROOT_PATH =
                    Environment.getExternalStorageDirectory().toString() + "/" + fileName + "/"
            } else {
                ROOT_PATH = Jlog.mConfig.writeRootPath
            }
            val rootFile = File(ROOT_PATH)
            try {
                if (!rootFile.exists()) {
                    rootFile.mkdir()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            val logPath = File("$ROOT_PATH/log/")
            try {
                if (!logPath.exists()) {
                    logPath.mkdir()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            val simpleDateFormat = SimpleDateFormat("yyyyMMdd", Locale.CHINA) // HH:mm:ss
            //获取当前时间
            val date = Date(System.currentTimeMillis())
            val logFile = File(logPath.toString() + "/" + simpleDateFormat.format(date) + ".txt")
            try {
                if (logPath.exists() && !logFile.exists()) {
                    logFile.createNewFile()
                }
            } catch (e: Exception) {
            }
            var fw: FileWriter? = null
            if (logFile.exists()) {
                try {
                    fw = FileWriter(logFile, true)
                    if (TextUtils.isEmpty(tag)) {
                        fw.write(timeString + "\t\t" + exceptionDescription + "\r\n")
                    } else {
                        fw.write(timeString + "\t\t" + tag + "\t\t" + exceptionDescription + "\r\n")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    fw?.close()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun getFileSizes(f: File): Long {
        var s: Long = 0
        if (f.exists()) {
            var fis: FileInputStream? = null
            try {
                fis = FileInputStream(f)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
            try {
                assert(fis != null)
                s = fis!!.available().toLong()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            try {
                f.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            println("文件不存在")
        }
        return s
    }

    /**
     * 获取时间
     *
     * @return str
     */
    val timeString: String
        get() {
            val dateStr = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
            return dateStr.format(Date())
        }
}